package org.jsola.hr.web;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsola.admin.core.AdminProperties;
import org.jsola.admin.vo.SiteVO;
import org.jsola.core.Result;
import org.jsola.hr.constant.ConfigCodeConstants;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.provider.IAdminProviderService;
import org.jsola.hr.provider.ISiteConfigProviderService;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.hr.vo.SystemConfigExtVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.jsola.user.vo.SystemConfigVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.regex.Pattern;


/**
 * 公司首页报名表
 *
 * @author zhr
 */
@Slf4j
@RestController("hrSiteController")
@RequestMapping(HrConstants.API_PATH + "/v1/site")
public class SiteController implements ISiteControllerAPI {

    @Autowired
    private IUserProviderService userProviderService;

    @Autowired
    private IAdminProviderService adminProviderService;

    @Autowired
    private AdminProperties adminProperties;

    @Autowired
    private ISiteConfigProviderService siteConfigProviderService;

    @Override
    @GetMapping(value = "/domain")
    public Result<SystemConfigVO> getSystemConfig() {


        //从spring容器里获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String host = request.getServerName();
        log.info("获取到host:" + host);
        SystemConfigVO systemConfigVO = userProviderService.selectSystemConfigByDomain(host);
        if (systemConfigVO == null) {
            return Result.success();
        }
        TokenUser tokenUser = UserContext.getUser();
        if (tokenUser == null) {
            return Result.success(
                    systemConfigVO
            );
        }
        SiteVO siteVO = adminProviderService.selectSiteById(tokenUser.getSiteId(), tokenUser);

        // 租户配置覆盖系统配置
        fillSiteSetting(systemConfigVO, siteVO);

        // 查询租户配置名称及图片
        return Result.success(
                systemConfigVO
        );
    }

    @Override
    @GetMapping(value = "/domain/free")
    public Result<SystemConfigExtVO> getSystemConfig4Login() {
        SystemConfigExtVO systemConfigExtVO = new SystemConfigExtVO();

        String xcxCode = siteConfigProviderService.selectValueByCode(ConfigCodeConstants.PC_COMPANY_SET_XCX_CODE, null);
        if (StringUtils.isBlank(xcxCode)){
            xcxCode = "zxr_xcx";
        }

        //从spring容器里获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String host = request.getServerName();

        log.info("获取到host:" + host);

        // 获取二级域名
        String secDomain = getSecDomain(host);
        log.info("获取到二级域名:" + secDomain);

        // host删除二级域名
        if (StringUtils.isNotBlank(secDomain)) {
            host = StringUtils.substring(host, secDomain.length() + 1);
        }
        log.info("过滤掉二级域名的host:" + host);

        SystemConfigVO systemConfigVO = userProviderService.selectSystemConfigByDomain(host);
        if (systemConfigVO == null) {
            return Result.success();
        }

        SiteVO siteVO = null;
        // 判断用户是否登录，如果已登录 优先使用siteId获取租户配置
        TokenUser tokenUser = UserContext.getUser();
        if (tokenUser != null) {
            siteVO = adminProviderService.selectSiteById(tokenUser.getSiteId(), tokenUser);
        } else {
            // 如果未登录根据二级域名获取租户配置
            // 二级域名为空 返回系统默认配置
            if (StringUtils.isBlank(secDomain)) {
                systemConfigExtVO = systemConfigVO.to(SystemConfigExtVO.class);
                systemConfigExtVO.setXcxCode(xcxCode);
                return Result.success(
                        systemConfigExtVO
                );
            }
            siteVO = adminProviderService.selectSiteBySecDomain(secDomain);
        }
        // 租户配置覆盖系统配置
        fillSiteSetting(systemConfigVO, siteVO);

        // 查询租户配置名称及图片
        systemConfigExtVO = systemConfigVO.to(SystemConfigExtVO.class);
        systemConfigExtVO.setXcxCode(xcxCode);
        return Result.success(
                systemConfigExtVO
        );
    }

    private void fillSiteSetting(SystemConfigVO systemConfigVO, SiteVO siteVO) {
        if (siteVO != null) {
            if (StringUtils.isNotBlank(siteVO.getSystemIcon())) {
                systemConfigVO.setSystemIcon(siteVO.getSystemIcon());
            }
            if (StringUtils.isNotBlank(siteVO.getLeftMenuHideLogoUrl())) {
                systemConfigVO.setLeftMenuHideLogoUrl(siteVO.getLeftMenuHideLogoUrl());
            }
            if (StringUtils.isNotBlank(siteVO.getDashboradLogoUrl())) {
                systemConfigVO.setDashboradLogoUrl(siteVO.getDashboradLogoUrl());
            }
            if (StringUtils.isNotBlank(siteVO.getPic())) {
                systemConfigVO.setSiteLogoUrl(siteVO.getPic());
            }
            if (StringUtils.isNotBlank(siteVO.getSystemBackground())) {
                systemConfigVO.setSystemBackground(siteVO.getSystemBackground());
            }
            if (StringUtils.isNotBlank(siteVO.getWebIcon())) {
                systemConfigVO.setWebIcon(siteVO.getWebIcon());
            }
            if (StringUtils.isNotBlank(siteVO.getWebTitle())) {
                systemConfigVO.setWebTitle(siteVO.getWebTitle());
            }
            if (StringUtils.isNotBlank(siteVO.getHomeLogo())) {
                systemConfigVO.setHomeLogo(siteVO.getHomeLogo());
            }

        }
    }

    /**
     * 根据传入域名获取二级域名
     *
     * @param host
     * @return
     */
    private String getSecDomain(String host) {
        // 按职薪人当前的域名进行以下判断，如果更换域名可能导致结果不准确
        // 判断是否职薪人的域名
        String zxrPattern = "(^zhixinren\\.work$)|(^.+\\.zhixinren\\.work$)";
        if (!Pattern.matches(zxrPattern, host)) {
            // 非职薪人域名 返回空字符串
            return StringUtils.EMPTY;
        }
        // 域名按'.'切割
        String[] split = StringUtils.split(host,'.');
        // 校验长度 长度<3 判断没有二级域名直接返回
        if (split.length < 3) {
            // 返回空字符串
            return StringUtils.EMPTY;
        } else {
            // 判断是否在预留名单中如果存在返回空
            if (adminProperties.getSite().getSecDomain().getReserve().contains(split[0])
                    || adminProperties.getSite().getSecDomain().getIllegal().contains(split[0])) {
                return StringUtils.EMPTY;
            }
            return split[0];
        }
    }


}

